package trieMatch.keywordMatcher;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import trieMatch.Interfaces.AtomFactory;

/**
 * Cached and synchronized AtomFactory.<br>
 * <br>
 * <b>NOTE:</b> Not generally used when storage is cheaper than cycle time.
 * 
 * @author mlrus
 * 
 */
public class DenseAtomFactory implements AtomFactory {
	final private static int SIZE = 128;
	static private List<Map<String, Atom>> singletonMap;
	static {
		singletonMap = new ArrayList<Map<String, Atom>>(SIZE);
		while (singletonMap.size() < SIZE) {
			singletonMap.add(new ConcurrentHashMap<String, Atom>());
		}
	}

	public Atom mkAtom(final String value, final int index) {
		final String fk = value.intern();
		if (singletonMap.size() < index) {
			synchronized (singletonMap) {
				while (singletonMap.size() <= index) {
					singletonMap.add(new ConcurrentHashMap<String, Atom>());
				}
			}
		}
		Atom atom = singletonMap.get(index).get(fk);
		if (atom == null) {
			atom = new Atom(fk, index);
			singletonMap.get(index).put(fk, atom);
		}
		return atom;
	};
}
